package com.ljh.account.controller;

import com.ljh.account.dao.Account;
import com.ljh.account.service.AccountService;
import com.ljh.account.utils.PasswdHash;
import com.ljh.account.utils.Response;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
public class AuthController {
    @Autowired
    AccountService accountService;


//    登录用户
    @PostMapping("/login")
    public Response login(@RequestBody Account account, HttpServletRequest request) {
        Account user = accountService.findAccountByName(account.getUsername());
        if (user == null) {
            return Response.error("用户名或者密码错误");
        }
        String relPwd = user.getPassword();

        if (PasswdHash.checkPassword(account.getPassword(),relPwd)){
//            登录成功后，将用户的ID用户名写入Session
            HttpSession session = request.getSession();
            session.setAttribute("username", user.getUsername());
            session.setAttribute("userId", user.getId());
            session.setAttribute("accountType", user.getAccountType());
            return Response.success("登录成功");
        }else{
            return Response.error("用户名或者密码错误");
        }
    }

    //    注册用户
    @PostMapping("/register")
    public Response register(@RequestBody Account account) {
        Account user = accountService.findAccountByName(account.getUsername());
        if (user != null){
            return Response.error("该用户已存在");
        }
        String passwd = account.getPassword();
        account.setPassword(PasswdHash.hashPassword(passwd));
        accountService.createAccount(account);
        return  Response.success("用户创建成功");
    }
    @GetMapping("/logout")
    public Response logout(HttpServletRequest request){
        HttpSession session = request.getSession();
        if (session != null) {
            session.invalidate(); // 清除会话
        }
        return Response.success("退出登录成功");
    }
}
